//
//  CSParsedXML.m
//  cactus-xml
//
//  Created by Yury Nikalayuk on 11.06.10.
//  Copyright 2011 CactusSoft. All rights reserved.
//

#import "CSParsedXML.h"
#import "../KissXML/DDXML.h"


@implementation CSParsedXML

@synthesize root;

-(id) init
{
	if(self = [super init])
	{
		root = nil;
	}
	return self;
}

-(void) dealloc
{
	[root release];
	[super dealloc];
}

-(BOOL) parse:(NSString *)location
{	
	NSString *xmlString = [[NSString alloc] initWithContentsOfFile:location
									encoding:NSUTF8StringEncoding error:NULL];
	BOOL result = [self parseWithData:xmlString];
	
	[xmlString release];
	return result;
}

-(BOOL) parseWithData:(NSString *)data
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	if(![data length])
	{
		[pool release];
		return NO;
	}
	NSError *theError = NULL;
	DDXMLDocument *theXMLDocument = [[DDXMLDocument alloc] 
									 initWithXMLString:data options:0 error:&theError];
	root = [[CSParsedXML buildNode:[theXMLDocument rootElement]] retain];
	[theXMLDocument release];
	[pool release];
	return YES;
	
}

+(CSXMLNode *) buildNode:(DDXMLNode *)source
{
	CSXMLNode *result = [[CSXMLNode alloc] initWithName:[source name] ];
	
	if([source kind] == DDXMLElementKind)
	{
		DDXMLElement *element = (DDXMLElement *) source;
		NSArray *attributes = [element attributes];
		for (DDXMLNode *attribute in attributes)
		{
			[result.attributes setObject:[attribute stringValue] forKey:[attribute name]];
		}
	}
	
	for(DDXMLNode *child in [source children])
	{
		switch([child kind])
		{
			case DDXMLElementKind:
			{
				CSXMLNode *childNode = [CSParsedXML buildNode:child];
				[result.children addObject:childNode];
			}
			break;
				
			case DDXMLTextKind:
			{
				result.value = [child stringValue];
			}
			break;
		}
	}
	return [result autorelease];
	
}
@end
